package scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * This class accepts a file and parses it for tokens. This token list can be returned for use elsewhere.
 * @author Justin
 *
 */
public class ScanFile {
	File myFile;
	Token head;
	/**
	 * Test Main
	 * @param args
	 */
	public static void main(String[] args){
		ScanFile myScan = new ScanFile("test.tst");
		myScan.scanIt();
		Token myHead = myScan.getTokens();
		while (myHead != null){
			//System.out.println(myHead.getWord());
			myHead = myHead.getNext();
		}
	}
	/**
	 * Instantiates the class, accepting a File
	 * @param File
	 */
	public ScanFile(File fileName){
		myFile = fileName;
	}
	/**
	 * Instantiates the class, accepting a String
	 * @param String
	 */
	public ScanFile(String fileName){
		myFile = new File(fileName);
	}
	/**
	 * Instantiates the class, accepting nothing
	 */
	public ScanFile(){
		
	}
	/**
	 * Sets the file to be used. Accepts a File
	 * @param File
	 */
	public void setFile(File fileName){
		myFile = fileName;
	}
	/**
	 * Sets the file to be used. Accepts a String
	 * @param String
	 */
	public void setFile(String fileName){
		myFile = new File(fileName);
	}
	/**
	 * Returns the current File
	 * @return File
	 */
	public File getFile(){
		return myFile;
	}
	/**
	 * Returns the first entry to the linked list of Tokens
	 * @return Token
	 */
	public Token getTokens(){
		return head;
	}
	/**
	 * Prints the String given.
	 * @param s
	 */
	public void println(String s){
		System.out.println(s);
	}
	/**
	 * Scans the file provided and breaks the file into a Linked List of tokens.
	 * Ignores '%' commented lines and blank lines.
	 * Use getTokens() to obtain the list.
	 */
	public void scanIt(){
		try {
			Scanner myScanner = new Scanner(myFile);
			head = null;
			Token currentToken = null;
			while(myScanner.hasNext()){
				String[] theLine = myScanner.nextLine().split("\\s+", 0); //creates a String array from the current line
				if (!theLine[0].equals("")){
					if (theLine[0].charAt(0) != '%'){
						for (int i = 0; i < theLine.length; i++){
							if (currentToken == null){
								head = currentToken = new Token(theLine[i]);
							}
							else{
								currentToken.setNext(new Token(theLine[i]));
								currentToken = currentToken.getNext();
							}
						}	
					}
				}
			}
			myScanner.close();
		} catch (FileNotFoundException e) {
			System.out.print("******************************************************************\n" + 
							"File Load Failure.\n" +
							"File \"" + myFile.getName() + "\" Should be verified for correctness.\n" + 
							"******************************************************************\n");
		}
	}
}
